﻿
using FreeSql;
using FreeSql.DataAnnotations;
using Ldt.CommonCapacitySupport.Business.Model;
using Ldt.DataEngine.DataFlowParse;
using Ldt.SettingCenter.Core;
using LDT.Task.JudgetDoc.Generation.DataBase;
using LdtCommonLibraryHttp;
using LdtJudge.DataEngine.CallInterface;
using LdtJudge.DataEngine.CallInterface.ConfiCenter;
using LdtJudge.DataEngine.CallInterface.ConfigManager;
using LdtJudge.DataEngine.Common;
using LdtJudge.DataEngine.Common.CommonWordHandle;
using LdtJudge.DataEngine.Data;
using LdtJudge.DataEngine.DataBaseStores;
using LdtJudge.DataEngine.DataBaseStores.Cached;
using LdtJudge.DataEngine.Model.Collection;
using LdtJudge.DataEngine.Model.CommModel;
using LdtJudge.DataEngine.Model.DataModel.CommonManageModel;
using LdtJudge.DataEngine.Model.DataModel.SysCommon;
using LdtJudge.DataEngine.Model.DataModel.SystemtableModel;
using LdtJudge.DataEngine.Model.OptimizationModel;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.XPath;

namespace Ldt.WindowsFormsApp
{

    public partial class FormMain : UIForm
    {
        // 进度条委托
        private ProcessShow processShow;
        private int keyWordIndex = 0;
        //private string settingCenterUrl = string.Empty;
        List<SYS_CaseType> sysCaseTypeTable = new List<SYS_CaseType>();
        List<SYS_CaseType_DocType> sysDocTypeTable = new List<SYS_CaseType_DocType>();
        IConfigRetrieval configRetrieval;
        bool inloading = false;
        DataContext dataContext;
        List<ConfigModel> modules = new List<ConfigModel>();
        /// <summary>
        /// 模块名称
        /// </summary>
        /// <param name="dataLayerStores"></param>
        public delegate void ModularModel(List<DataEngine.DataFlowParse.Model.ConfigModel> configModels);

        /// <summary>
        /// 模块数据结果
        /// </summary>
        public delegate HandleResultModel HandleResultShow();

        public HandleResultShow GetHandleResult;

        public Dictionary<string, object> dicTable = new Dictionary<string, object>();

        HttpHelper httpHelper;

        /// <summary>
        /// 配置信息
        /// </summary>
        private IConfiguration _configuration;

        public FormMain(HttpHelper httpHelper)
        {
            InitializeComponent();
            this.httpHelper = httpHelper;
            filePathTextBox.ReadOnly = true;
            filePathTextBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(243)))), ((int)(((byte)(255)))));
            filePathTextBox.RectColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(243)))), ((int)(((byte)(255)))));
            filePathTextBox.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(235)))), ((int)(((byte)(243)))), ((int)(((byte)(255)))));
            comboBoxcasetype.TreeView.CheckBoxes = false;
            comboBoxSourceName.TreeView.CheckBoxes = false;
            comboBoxcasetype.DropDownStyle = ComboBoxStyle.DropDown;
            this.dataGridView1.AutoGenerateColumns = false;
            ToolStripMenuItem themeItem = new ToolStripMenuItem("更换主题");
            var styles = UIStyles.PopularStyles();
            foreach (UIStyle style in styles)
            {
                ToolStripMenuItem item = new ToolStripMenuItem(style.DisplayText()) { Tag = style };
                item.Click += Item_Click;
                themeItem.DropDownItems.Add(item);
            }
            menuStrip1.Items.Add(themeItem);
        }

        private void Item_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            if (item.Tag != null && item.Tag is UIStyle style)
            {
                this.Style = style;
            }
        }

        /// <summary>
        /// 窗体加载事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FormMain_Load(object sender, EventArgs e)
        {
            _configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();
            ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(_configuration);
            //settingCenterUrl = configManagerHandle.Settingcenter;ConfigManagerHandle.Appcode
            ISettingCenter settingCenter = (ISettingCenter)DbHelper.ServiceProvider.GetService(typeof(ISettingCenter));
            var ta = Task.Run(() => { configRetrieval = new ConfigRetrieval(_configuration, configManagerHandle, settingCenter); });
            ta.Wait();
            LoadSysCaseTypeData();
            comboBoxcasetype.TreeView.AfterExpand += TreeView_AfterExpandCaseType;
            GetcomboSourceName();
            LoadCommonManageData();
        }
        public static Type[] GetTypesByTableAttribute()
        {
            List<Type> tableAssembies = new List<Type>();
            foreach (Type type in Assembly.GetAssembly(typeof(ArgumentRel)).GetExportedTypes())
            {
                if (type.Name == "ArgumentRel")
                {
                    string f = "";
                }
                foreach (Attribute attribute in type.GetCustomAttributes())
                {
                    if (attribute is TableAttribute tableAttribute)
                        if (tableAttribute.DisableSyncStructure == false)
                            tableAssembies.Add(type);
                }

            }
            return tableAssembies.ToArray();
        }


        public static void CacheDataLoade(string code)
        {
            if (code == "LdtCommonManage")
            {
                #region commonManager数据缓存



                var myfreesql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("LdtCommonManage");
                var sqlitefreesql = new FreeSqlBuilder().UseConnectionString(DataType.Sqlite, "Data Source=:memory:").Build();
                sqlitefreesql.CodeFirst.IsAutoSyncStructure = true;

                sqlitefreesql.CodeFirst.SyncStructure<RiuParameterList>();
                List<RiuParameterList> riuParameterLists = myfreesql.Select<RiuParameterList>()?.ToList();
                sqlitefreesql.Insert<RiuParameterList>(riuParameterLists).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<ArgumentRel>();
                List<ArgumentRel> argumentRelList = myfreesql.Select<ArgumentRel>()?.ToList();
                sqlitefreesql.Insert<ArgumentRel>(argumentRelList).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<ConvertMode>();
                List<ConvertMode> convertsList = myfreesql.Select<ConvertMode>()?.ToList();
                sqlitefreesql.Insert<ConvertMode>(convertsList).ExecuteAffrows();

                sqlitefreesql.CodeFirst.SyncStructure<ElementExtractSource>();
                List<ElementExtractSource> elementExtractSources = myfreesql.Select<ElementExtractSource>()?.ToList();
                sqlitefreesql.Insert<ElementExtractSource>(elementExtractSources).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<ExtractFeature>();
                List<ExtractFeature> extractFeatures = myfreesql.Select<ExtractFeature>()?.ToList();
                sqlitefreesql.Insert<ExtractFeature>(extractFeatures).ExecuteAffrows();

                sqlitefreesql.CodeFirst.SyncStructure<ExtractInfo>();
                List<ExtractInfo> extractInfos = myfreesql.Select<ExtractInfo>()?.ToList();
                sqlitefreesql.Insert<ExtractInfo>(extractInfos).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RegInfoUintParameterConfig>();
                List<RegInfoUintParameterConfig> regInfoUintParameterConfigs = myfreesql.Select<RegInfoUintParameterConfig>()?.ToList();
                sqlitefreesql.Insert<RegInfoUintParameterConfig>(regInfoUintParameterConfigs).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RegInfoUintParameterRelation>();
                List<RegInfoUintParameterRelation> regInfoUintParameterRelations = myfreesql.Select<RegInfoUintParameterRelation>()?.ToList();
                sqlitefreesql.Insert<RegInfoUintParameterRelation>(regInfoUintParameterRelations).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RegInfoUnit>();
                List<RegInfoUnit> regInfoUnits = myfreesql.Select<RegInfoUnit>()?.ToList();
                sqlitefreesql.Insert<RegInfoUnit>(regInfoUnits).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RegRegexs>();
                List<RegRegexs> regRegexList = myfreesql.Select<RegRegexs>()?.ToList();
                sqlitefreesql.Insert<RegRegexs>(regRegexList).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RegRegexsHistory>();
                List<RegRegexsHistory> regRegexsHistories = myfreesql.Select<RegRegexsHistory>()?.ToList();
                sqlitefreesql.Insert<RegRegexsHistory>(regRegexsHistories).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<ReturnMode>();
                List<ReturnMode> returnModes = myfreesql.Select<ReturnMode>()?.ToList();
                sqlitefreesql.Insert<ReturnMode>(returnModes).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RiuAIRule>();
                List<RiuAIRule> riuAIRules = myfreesql.Select<RiuAIRule>()?.ToList();
                sqlitefreesql.Insert<RiuAIRule>(riuAIRules).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RiuCodeRule>();
                List<RiuCodeRule> riuCodeRules = myfreesql.Select<RiuCodeRule>()?.ToList();
                sqlitefreesql.Insert<RiuCodeRule>(riuCodeRules).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RiuHistoryInfo>();
                List<RiuHistoryInfo> riuHistoryInfos = myfreesql.Select<RiuHistoryInfo>()?.ToList();
                sqlitefreesql.Insert<RiuHistoryInfo>(riuHistoryInfos).ExecuteAffrows();

                sqlitefreesql.CodeFirst.SyncStructure<RiuRegexs>();
                List<RiuRegexs> riuRegexs = myfreesql.Select<RiuRegexs>()?.ToList();
                sqlitefreesql.Insert<RiuRegexs>(riuRegexs).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RiuRuleRelation>();
                List<RiuRuleRelation> riuRuleRelations = myfreesql.Select<RiuRuleRelation>()?.ToList();
                sqlitefreesql.Insert<RiuRuleRelation>(riuRuleRelations).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RuleInfoParmeterRelation>();
                List<RuleInfoParmeterRelation> ruleInfoParmeterRelations = myfreesql.Select<RuleInfoParmeterRelation>()?.ToList();
                sqlitefreesql.Insert<RuleInfoParmeterRelation>(ruleInfoParmeterRelations).ExecuteAffrows();


                sqlitefreesql.CodeFirst.SyncStructure<RuleInfoUnit>();
                List<RuleInfoUnit> ruleInfoUnits = myfreesql.Select<RuleInfoUnit>()?.ToList();
                sqlitefreesql.Insert<RuleInfoUnit>(ruleInfoUnits).ExecuteAffrows();


                LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.UpdateFreeSql("LdtCommonManage", sqlitefreesql);
                #endregion

            }

        }
        private void LoadCommonManageData()
        {
            //CacheDataLoade("LdtCommonManage");

            IFreeSql ManagefreeSql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("LdtCommonManage");

            List<ExtractInfo> extractInfoList = ManagefreeSql.Select<ExtractInfo>().ToList();
            dicTable.Add("ExtractInfo", extractInfoList);

            List<ExtractFeature> extractFeatureList = ManagefreeSql.Select<ExtractFeature>().ToList();
            dicTable.Add("ExtractFeature", extractFeatureList);

            List<ElementExtractSource> elementExtractSourceList = ManagefreeSql.Select<ElementExtractSource>().ToList();
            dicTable.Add("ElementExtractSource", elementExtractSourceList);

            List<RuleInfoUnit> ruleInfoUnitList = ManagefreeSql.Select<RuleInfoUnit>().ToList();
            dicTable.Add("RuleInfoUnit", ruleInfoUnitList);

            List<ConvertMode> convertmodeList = ManagefreeSql.Select<ConvertMode>().ToList();
            dicTable.Add("ConvertMode", convertmodeList);
            IFreeSql sysfreeSql = LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetFreeSQL("Ldt_JudgeDocSystem");
            List<MSYS_Express_Source> express_SourcesList = sysfreeSql.Select<SYS_Express_Source, LdtJudge.DataEngine.Model.DataModel.SystemtableModel.SYS_Argument>().InnerJoin((a, b) => a.ES_Purpose == b.AM_ID).ToList<MSYS_Express_Source>();
            dicTable.Add("MSYS_Express_Source", express_SourcesList);

            MsysExpressSourceCached.Initialization(express_SourcesList);
        }

        /// <summary>
        /// 加载案件数据
        /// </summary>
        private void LoadSysCaseTypeData()
        {
            SqlSysCommon sqlSysCommon = new SqlSysCommon("");
            sysCaseTypeTable = sqlSysCommon.GetCaseType();

            if (sysCaseTypeTable.Count > 0)
            {
                if (sysCaseTypeTable.Where(a => a.CT_ParentID == null || a.CT_ParentID == "")?.ToList().Count > 0)
                {
                    comboBoxcasetype.TreeView.Nodes.Clear();
                    var sysCaseTypedt = sysCaseTypeTable.Where(a => a.CT_ParentID == null || a.CT_ParentID == "")?.ToList();
                    foreach (var dr in sysCaseTypedt)
                    {
                        TreeNode node = new TreeNode() { Text = dr.CT_Name.ToString(), Name = dr.CaseTypeID.ToString(), Tag = dr.CT_Code.ToString() };
                        if (sysCaseTypeTable.Where(a => a.CT_ParentID == node.Name)?.ToList().Count > 0)
                        {
                            node.Nodes.Add(new TreeNode());
                        }
                        comboBoxcasetype.TreeView.Nodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 获取文书类型
        /// </summary>
        private void LoadCaseDocType()
        {
            SqlSysCommon sqlSysCommon = new SqlSysCommon("");
            if (!string.IsNullOrEmpty(comboBoxcasetype.Text))
            {
                if (sysCaseTypeTable.Where(a => a.CaseTypeID == comboBoxcasetype.TreeView.SelectedNode.Name)?.ToList().Count > 0)
                {
                    comboBoxSourceName.Text = "";
                    comboBoxSourceName.TreeView.Nodes.Clear();
                    string code = sysCaseTypeTable.Where(a => a.CaseTypeID == comboBoxcasetype.TreeView.SelectedNode.Name)?.ToList()[0].CT_Code.ToString();
                    sysDocTypeTable = sqlSysCommon.GetDocTypeDataByCaseTypeID(code);
                    if (sysDocTypeTable != null && sysDocTypeTable.Count > 0)
                    {
                        foreach (SYS_CaseType_DocType dr in sysDocTypeTable)
                        {
                            TreeNode node = new TreeNode() { Text = dr.CD_Name.ToString(), Name = dr.CD_Name.ToString(), Tag = dr.CD_Code.ToString() };
                            comboBoxSourceName.TreeView.Nodes.Add(node);
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 加载文书类型
        /// </summary>
        private void LoadCaseDocType_new()
        {
            SqlSysCommon sqlSysCommon = new SqlSysCommon("");
            if (inloading) return;
            if (!string.IsNullOrEmpty(comboBoxcasetype.Text))
            {
                comboSourceName.SelectionStart = comboSourceName.Text.Length;
                if (sysCaseTypeTable.Where(a => a.CaseTypeID == comboBoxcasetype.TreeView.SelectedNode.Name)?.ToList().Count > 0)
                {

                    comboSourceName.Items.Clear();
                    string code = sysCaseTypeTable.Where(a => a.CaseTypeID == comboBoxcasetype.TreeView.SelectedNode.Name)?.ToList()[0].CT_Code.ToString();
                    sysDocTypeTable = sqlSysCommon.GetDocTypeDataByCaseTypeID(code);
                    string s = comboSourceName.Text;
                    int n = comboSourceName.SelectionStart;
                    //sysDocTypeTable = sysDocTypeTable.Select("name='量刑建议书'").CopyToDataTable();
                    if (sysDocTypeTable != null && sysDocTypeTable.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(s))
                        {
                            if (sysDocTypeTable.Where(a => a.CD_Name.IndexOf(s) > -1)?.ToList().Count > 0)
                            {
                                sysDocTypeTable = sysDocTypeTable.Where(a => a.CD_Name.IndexOf(s) > -1)?.ToList();
                            }
                        }

                        foreach (var dr in sysDocTypeTable)
                        {
                            comboSourceName.Items.Add(dr.CD_Name.ToString().Trim() + "-" + dr.CD_Code.ToString().Trim());
                        }
                        inloading = true;
                        comboSourceName.Text = s;
                        Application.DoEvents();
                        comboSourceName.SelectionStart = n;
                        inloading = false;
                    }
                }
            }

        }

        private void TreeView_AfterExpandCaseType(object sender, TreeViewEventArgs e)
        {
            e.Node.Nodes.Clear();
            if (sysCaseTypeTable.Where(a => a.CT_ParentID == e.Node.Name)?.ToList().Count > 0)
            {
                var dt = sysCaseTypeTable.Where(a => a.CT_ParentID == e.Node.Name)?.ToList();
                if (dt != null && dt.Count > 0)
                {
                    foreach (var dr in dt)
                    {
                        TreeNode node = new TreeNode { Text = dr.CT_Name.ToString(), Name = dr.CaseTypeID.ToString(), Tag = dr.CT_Code.ToString() };
                        if (sysCaseTypeTable.Where(a => a.CT_ParentID == node.Name)?.ToList().Count > 0)
                        {
                            var dtt = sysCaseTypeTable.Where(a => a.CT_ParentID == node.Name)?.ToList();
                            if (dtt != null && dtt.Count > 0)
                            {
                                node.Nodes.Add(new TreeNode());
                            }
                        }
                        e.Node.Nodes.Add(node);
                    }
                }
            }
        }

        /// <summary>
        /// 案件类型选择
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBoxcasetype_TextChanged(object sender, EventArgs e)
        {
            if (comboBoxcasetype.TreeView.SelectedNode.Nodes.Count > 0)
            {
                comboBoxcasetype.Text = "";
                ShowWarningDialog("选择的案件类型无效，请重新选择！");
            }
            else
            {
                try
                {
                    LoadCaseDocType();
                    LoadCaseDocType_new();
                    this.comboSourceName.SelectedIndex = 0;
                    if (!string.IsNullOrEmpty(comboBoxcasetype.Text) && !string.IsNullOrEmpty(comboSourceName.Text))
                        buttonImport.Enabled = true;
                }
                catch (Exception)
                {
                    ShowErrorDialog("无可分析文书，请重新选择");
                }
            }
        }

        /// <summary>
        /// 进行文书导入
        /// </summary>
        /// <param name="sender"> sender</param>
        /// <param name="e"> e </param>
        private void buttonImport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(comboBoxcasetype.Text) && !string.IsNullOrWhiteSpace(comboSourceName.Text))
            {
                labelProgress.Text = "";
                //文件选择
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Multiselect = false;
                fileDialog.Title = "请选择文件";
                fileDialog.Filter = "所有文件(*.doc,*.docx,*.rtf)|*.doc;*.docx;*.rtf;";
                var test = configRetrieval.GetLogPath();
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    modules.Clear();
                    richTextBoxLog.Text = "";
                    dataGridView1.DataSource = "";
                    LdtDataEngin.ModuleDetail.CommonModule.DataDeduceDetail.DeduceRequestModels.Clear();
                    filePathTextBox.Text = fileDialog.FileName;
                    WordHandle wordHandle = new WordHandle();

                    string content = wordHandle.GetWordContent(fileDialog.FileName);
                    string appid = uiTextAppid.Text.ToString();
                    string casetype = comboBoxcasetype.Text;
                    string sourcename = comboSourceName.Text.Split('-')[1];
                    string fileName = new FileInfo(fileDialog.FileName).Name;  //文件名
                    string caseOnlyID = System.Text.RegularExpressions.Regex.Match(fileName, @".*(?=[（(_-].*?[)）]?\.doc)").Value;
                    string district = TextBoxDistrict.Text ?? configRetrieval.GetAppSettingString("district");
                    string caseCause = txbCaseCause.Text.Trim();
                    textBoxCaseOnlyID.Text = caseOnlyID;
                    Task.Factory.StartNew(() =>
                    {
                        Stopwatch swtext = new Stopwatch();
                        swtext.Start();
                        string bcxml = "";
                        if (!string.IsNullOrEmpty(uiTextBox1.Text))
                        {
                            bcxml = uiTextBox1.Text;
                        }
                        MainInputParameterModel inputParameter = new MainInputParameterModel()
                        {
                            CaseType = casetype,
                            DocID = sourcename,
                            SourceContent = content,
                            SD_CaseOnlyID = caseOnlyID,
                            FilePath = "",
                            CaseCause = caseCause,
                            CourtId = "",
                            AppId = appid,
                            CaseID = caseOnlyID,
                            FL_ID = "",
                            SF_ID = "",
                            District = district,
                            BCXml = bcxml,
                            IsSave = true,
                            dicTabel = dicTable,
                        };
                        ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
                        DataEngin.Assemble.MainComponentBase main = new DataEngin.Assemble.MainComponentBase(configFlowLoad);
                        main.inputParameter = inputParameter;
                        main.LogShow = new LogShow(LogMessage);
                        main.ProcessShow = new ProcessShow(SetProcess);
                        main.ModuleProcessShow = new ModuleProcessShow(SetModuleProcess);

                        // 执行分析
                        main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
                        ShowFlowModules(main.configmodels);

                        main.ExtractWrap();

                        dataContext = main.dataContext;
                        swtext.Stop();
                        SetlabelMNText(",总耗时" + (swtext.ElapsedMilliseconds / 1000).ToString("0") + "秒");
                    });

                    uiSymbolButton1.Enabled = true;
                }
            }
        }

        /// <summary>
        /// 对接调度分析数据
        /// </summary>
        /// <param name="message"></param>
        public void TestAnalysisServer(string message, object froms)
        {
            FormBack formBack = (FormBack)froms;
            formBack.Close();
            string state = "1";
            FileExtractModel fileExtractModel = JsonConvert.DeserializeObject<FileExtractModel>(message.Replace("&#x13;", "").Replace("&#x14;", "").Replace("&#x15;", "").Replace("&#xD;", ""));
            fileExtractModel.MsgState = "0";
            var _configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();
            ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(_configuration);
            ISettingCenter settingCenter = (ISettingCenter)DbHelper.ServiceProvider.GetService(typeof(ISettingCenter));
            var ta = Task.Run(() => { configRetrieval = new ConfigRetrieval(_configuration, configManagerHandle, settingCenter); });
            ta.Wait();
            try
            {
                //交互实体
                BufferModel bufferModel = new BufferModel();
                List<DocInfol> DocInfolList = new List<DocInfol>();
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "mssuitbook").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws010003614").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws010000050").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws0100011427").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws010000776").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "ws0100015457").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "xssuitbook").ToList());
                DocInfolList.AddRange(fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() == "xzsuitbook").ToList());
                if (fileExtractModel.DocInfos.FirstOrDefault(a => a.SourceCode != "mssuitbook" && a.SourceCode != "xssuitbook" && a.SourceCode != "xzsuitbook" && a.SourceCode.ToLower() != "ws010003614" && a.SourceCode.ToLower() != "ws010000050" && a.SourceCode.ToLower() != "ws0100011427" && a.SourceCode.ToLower() != "ws010000776" && a.SourceCode.ToLower() != "ws0100015457") != null)
                {
                    foreach (DocInfol infol in fileExtractModel.DocInfos.Where(a => a.SourceCode.ToLower() != "mssuitbook" && a.SourceCode.ToLower() != "xssuitbook" && a.SourceCode.ToLower() != "xzsuitbook" && a.SourceCode.ToLower() != "ws010003614" && a.SourceCode.ToLower() != "ws010000050" && a.SourceCode.ToLower() != "ws0100011427" && a.SourceCode.ToLower() != "ws010000776" && a.SourceCode.ToLower() != "ws0100015457").ToList())
                    {
                        DocInfolList.Add(infol);
                    }
                }
                for (int i = 0; i < DocInfolList.Count; i++)
                {
                    DocInfol docInfol = DocInfolList[i];
                    try
                    {
                        string docPath = docInfol.FileUrl;
                        bufferModel.OutRelatID = fileExtractModel.CaseInfo.OutRealtId;
                        bufferModel.SourceName = docInfol.SourceCode;
                        bufferModel.MsgId = fileExtractModel.MsgId;
                        bufferModel.HandleType = "1";
                        bufferModel.FilePath = docInfol.FileId;
                        bufferModel.SourceCode = docInfol.SourceCode;
                        bufferModel.SourceID = docInfol.SFID;

                        System.Runtime.CallContext.SetData("systemplatform", ConfigManagerHandle.PlatFormName.wordparse_analysisservice);
                        System.Runtime.CallContext.SetData("baseDirectory", configRetrieval.GetLogPath());
                        System.Runtime.CallContext.SetData("identifier", bufferModel.OutRelatID.ToLower());//当前案件唯一ID
                        System.Runtime.CallContext.SetData("typename", bufferModel.SourceCode.ToLower());//当前分析的文书名称
                        System.Runtime.CallContext.SetData("customid", Thread.CurrentThread.ManagedThreadId.ToString());//当前标识ID
                        WordHandle wordHandle = new WordHandle();
                        string content = "";
                        if (!string.IsNullOrEmpty(docPath))
                        {
                            try
                            {

                                LogMessage("获取文件流路径：" + docPath, LogMessageType.Info);
                                content = wordHandle.GerBysetWrodContext(docPath);
                            }
                            catch (Exception exf)
                            {

                                LogMessage("文件流获取文本错误：" + exf.ToString(), LogMessageType.Info);
                                throw;
                            }
                        }
                        else
                        {
                            LogMessage("文件路径为空！！！", LogMessageType.Info);
                        }
                        if (!string.IsNullOrEmpty(content))
                        {


                            MainInputParameterModel inputParameter = new MainInputParameterModel()
                            {
                                CaseType = fileExtractModel.CaseInfo.CaseType,
                                DocID = bufferModel.SourceCode,
                                SourceContent = content,
                                SD_CaseOnlyID = bufferModel.OutRelatID,
                                FilePath = "",
                                CaseCause = fileExtractModel.CaseInfo.CaseCause,
                                CourtId = "",
                                AppId = "",
                                CaseID = fileExtractModel.CaseInfo.CaseId,
                                FL_ID = docInfol.FileId,
                                SF_ID = docInfol.SFID,
                                laststage = fileExtractModel.laststage,
                                IsSave = true,
                                District = fileExtractModel.District,
                                BCXml = docInfol.BackXml
                            };
                            ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
                            Ldt.DataEngin.Assemble.MainComponentBase main = new Ldt.DataEngin.Assemble.MainComponentBase(configFlowLoad);
                            main.inputParameter = inputParameter;
                            main.LogShow = new LogShow(LogMessage);
                            main.ProcessShow = new ProcessShow(SetProcess);
                            main.ModuleProcessShow = new ModuleProcessShow(SetModuleProcess);
                            // 执行分析
                            main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
                            ShowFlowModules(main.configmodels);
                            main.ExtractWrap();
                            docInfol.MsgState = "1";
                        }
                    }
                    catch (Exception e)
                    {

                        docInfol.MsgState = "0";
                        docInfol.ErrMessage = e.Message.ToString() + e.ToString();
                    }
                }
            }
            catch (Exception e)
            {
                state = "0";
                LogMessage("分析完成失败：错误消息内容为：" + e.Message, LogMessageType.Info);
                LogMessage("分析完成失败：错误消息内容为：" + e.StackTrace, LogMessageType.Info);
                LogMessage("分析完成失败：TextExtractionFinishedQueue发送消息内容为：" + message, LogMessageType.Info);
            }
            finally
            {
                //错误消息内容
                string errormsg = string.Empty;
                try
                {

                }
                catch (Exception exs)
                {
                    errormsg += exs.Message;
                }
                if (!string.IsNullOrWhiteSpace(errormsg))
                {
                    LogMessage("分析完成错误：消息内容为：" + errormsg, LogMessageType.Info);
                }

            }

        }

        public void Publicserver(string message, object froms)
        {
            FormBack formBack = (FormBack)froms;
            formBack.Close();
            AnalysisDocModel analysisDocModel = JsonConvert.DeserializeObject<AnalysisDocModel>(message);
            AnalysisSourceDoc("", analysisDocModel, true);


        }

        public bodyModel AnalysisSourceDoc(string anjid, AnalysisDocModel analysisDoc, bool dunluo)
        {
            Stopwatch swtext = new Stopwatch();
            swtext.Start();
            bodyModel bodymodel = new bodyModel();
            anjid = Snowflake.Instance().GetId().ToString();
            string sourceContent = string.Empty;
            if (analysisDoc.DocType == 0)
            {
                byte[] filestream = Convert.FromBase64String(analysisDoc.DocFile);
                sourceContent = BllDataHandle.GetDocText(filestream);
            }
            else if (analysisDoc.DocType == 1)
            {
                byte[] filestream = Convert.FromBase64String(analysisDoc.DocFile);
                sourceContent = Encoding.Default.GetString(filestream);
            }
            MainInputParameterModel inputParameter = new MainInputParameterModel()
            {
                CaseType = analysisDoc.Anjlx,
                DocID = analysisDoc.Juanzbh,
                SourceContent = sourceContent,
                SD_CaseOnlyID = anjid,
                FilePath = "",
                CaseCause = analysisDoc.Anyid,
                CourtId = "",
                AppId = analysisDoc.AppId,
                CaseID = anjid,
                FL_ID = "",
                SF_ID = "",
                IsSave = false
            };
            ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
            DataEngin.Assemble.MainComponentBase main = new DataEngin.Assemble.MainComponentBase(configFlowLoad);
            main.inputParameter = inputParameter;
            main.LogShow = new LogShow(LogMessage1);
            main.ProcessShow = new ProcessShow(SetProcess);
            main.ModuleProcessShow = new ModuleProcessShow(SetModuleProcess);
            // 执行分析
            main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
            ShowFlowModules(main.configmodels);
            main.ExtractWrap();
            if (main.dataContext.DataLayerOpt != null && main.dataContext.DataLayerOpt.OptimizationXml != null)
            {
                bodymodel.anjianyaosu = main.dataContext.DataLayerOpt.OptimizationXml.OuterXml;

            }
            if (dunluo)
            {
                string json = JsonConvert.SerializeObject(main.dataContext.DataLayerAns.Duanluos);
                bodymodel.an_Duanluos = main.dataContext.DataLayerAns.Duanluos;
            }
            swtext.Stop();
            SetlabelMNText(",总耗时" + (swtext.ElapsedMilliseconds / 1000).ToString("0") + "秒");
            return bodymodel;
        }

        /// <summary>
        /// 管辖案件数据回填优选
        /// </summary>
        /// <param name="">从MQ获取到的数据</param>
        public void FillBackOpt(string message, object froms)
        {
            FormBack formBack = (FormBack)froms;
            formBack.Close();
            Stopwatch swtext = new Stopwatch();
            swtext.Start();
            var _configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();
            ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(_configuration);
            //settingCenterUrl = configManagerHandle.Settingcenter;ConfigManagerHandle.Appcode
            ISettingCenter settingCenter = (ISettingCenter)DbHelper.ServiceProvider.GetService(typeof(ISettingCenter));
            var ta = Task.Run(() => { configRetrieval = new ConfigRetrieval(_configuration, configManagerHandle, settingCenter); });
            ta.Wait();
            IConfiguration configuration = _configuration;
            //进行配置分析服务的最大线程
            string state = "1";
            Dictionary<string, object> dicValue = new Dictionary<string, object>();
            //交互实体
            FileExtractModel fileExtractModel = new FileExtractModel();
            FillBackOptParameterModel fillBackOptParameter = JsonConvert.DeserializeObject<FillBackOptParameterModel>(message);
            fileExtractModel.MsgId = fillBackOptParameter.MsgId;
            fileExtractModel.CaseInfo = new LdtJudge.DataEngine.Model.Collection.CaseInfo();
            fileExtractModel.CaseInfo.OutRealtId = fillBackOptParameter.Outrelatid;
            fileExtractModel.CaseInfo.CaseId = fillBackOptParameter.CaseID;
            try
            {
                if (fillBackOptParameter.Contents != null && fillBackOptParameter.Contents.Count > 0)
                {
                    #region 旧回填方法
                    //foreach (var datacontext in fillBackOptParameter.Contents)
                    //{
                    //    Stopwatch swtext1 = new Stopwatch();
                    //    swtext1.Start();
                    //    try
                    //    {
                    //        Ldt.DataEngin.Assemble.Main main = new Ldt.DataEngin.Assemble.Main();
                    //        main.configRetrieval = configRetrieval;
                    //        main.Loading(fillBackOptParameter.CaseType, fillBackOptParameter.CourtID, fillBackOptParameter.Outrelatid, fillBackOptParameter.AppId, datacontext.SourceCode, fillBackOptParameter.CCIDs, fillBackOptParameter.CaseID);
                    //        main.LogShow = new LogShow(LogMessage);
                    //        main.ProcessShow = new ProcessShow(SetProcess);
                    //        main.ModuleProcessShow = new ModuleProcessShow(SetModuleProcess);
                    //        main.configRetrieval = configRetrieval;
                    //        main.IsEvidence = datacontext.IsEvidence;
                    //        main.FillBackOptimization(datacontext.Content, fillBackOptParameter.CaseType, fillBackOptParameter.CourtID, fillBackOptParameter.Outrelatid, fillBackOptParameter.AppId, datacontext.SourceCode, fillBackOptParameter.laststage, "", datacontext.EvidenceXpathList, fillBackOptParameter.CCIDs);
                    //        fillBackOptParameter.MsgState = "1";
                    //        fileExtractModel.MsgState = "1";
                    //    }
                    //    catch (Exception  ff)
                    //    {

                    //        string b = "1";
                    //    }
                    //    swtext1.Stop();
                    //    WriteLog(datacontext.SourceCode + "分析时长" + (swtext1.ElapsedMilliseconds / 1000).ToString("0") + "秒", "\\log\\log.txt", false);

                    //}
                    #endregion

                    Ldt.DataEngin.Assemble.Main main = new Ldt.DataEngin.Assemble.Main();
                    main.configRetrieval = configRetrieval;
                    main.LogShow = new LogShow(LogMessage);
                    main.ProcessShow = new ProcessShow(SetProcess);
                    main.ModuleProcessShow = new ModuleProcessShow(SetModuleProcess);
                    main.configRetrieval = configRetrieval;
                    main.FillBackOptimization(fillBackOptParameter);
                }
            }
            catch (Exception ex)
            {
                fileExtractModel.MsgState = "0";
                state = "0";
                dicValue.Add("CaseID", fillBackOptParameter.CaseID);
                dicValue.Add("OutRelateId", fillBackOptParameter.Outrelatid);
                dicValue.Add("CaseTypeId", fillBackOptParameter.CaseType);
                dicValue.Add("State", state);
                dicValue.Add("MsgId", fillBackOptParameter.MsgId);
                fillBackOptParameter.MsgState = "0";
            }
            swtext.Stop();
            WriteLog("分析总时长" + (swtext.ElapsedMilliseconds / 1000).ToString("0") + "秒", "\\log\\log.txt", false);
        }

        /// <summary>
        /// 段落分析
        /// </summary>
        /// <param name="message">消息体</param>
        /// <param name="froms">from窗体</param>
        public void ParagraphAnalysis(string message,object froms)
        {
            FormBack formBack = (FormBack)froms;
            formBack.Close();
            Stopwatch swtext = new Stopwatch();
            swtext.Start();
            var _configuration = new ConfigurationBuilder().SetBasePath(System.AppContext.BaseDirectory).AddJsonFile("appsettings.json", true, true).Build();
            ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(_configuration);
            //settingCenterUrl = configManagerHandle.Settingcenter;ConfigManagerHandle.Appcode
            ISettingCenter settingCenter = (ISettingCenter)DbHelper.ServiceProvider.GetService(typeof(ISettingCenter));
            var ta = Task.Run(() => { configRetrieval = new ConfigRetrieval(_configuration, configManagerHandle, settingCenter); });
            ta.Wait();
            IConfiguration configuration = _configuration;
            ParagraphExtractModel paragraphExtractModel = JsonConvert.DeserializeObject<ParagraphExtractModel>(message);
            try
            {
                MainInputParameterModel inputParameter = new MainInputParameterModel()
                {
                    CaseType = paragraphExtractModel.CaseType,
                    DocID = paragraphExtractModel.SourceCode,
                    SD_CaseOnlyID = paragraphExtractModel.OutRealtId,
                    FilePath = "",
                    CaseCause = paragraphExtractModel.CaseCause,
                    CourtId = "",
                    AppId = paragraphExtractModel.AppId,
                    CaseID = paragraphExtractModel.CaseId,
                    laststage = paragraphExtractModel.laststage,
                    IsSave = true,
                    District = paragraphExtractModel.District,
                    BCXml = paragraphExtractModel.BackXml,
                    IsParagraphAnalysis = true,
                    ParagraphModels = paragraphExtractModel.Paragraphs
                };
                ConfigFlowLoad configFlowLoad = new ConfigFlowLoad();
                Ldt.DataEngin.Assemble.MainComponentBase main = new Ldt.DataEngin.Assemble.MainComponentBase(configFlowLoad);
                main.inputParameter = inputParameter;
                main.LogShow = new LogShow(LogMessage);
                main.ProcessShow = new ProcessShow(SetProcess);
                main.ModuleProcessShow = new ModuleProcessShow(SetModuleProcess);
                // 执行分析
                main.GetFlowConfig(ConfigFlowLoad.FlowType.Ana);
                if (inputParameter.IsParagraphAnalysis == true)
                {
                    main.configmodels = main.configmodels.Where(x => !x.Code.ToLower().Contains("moudletextformattingextract") && !x.Code.ToLower().Contains("moudleparagraphextract")).ToList();
                }
                ShowFlowModules(main.configmodels);
                main.ExtractWrap();
                paragraphExtractModel.MsgState = "1";
            }
            catch (Exception ex)
            {
                paragraphExtractModel.MsgState = "0";
            }
            
            swtext.Stop();
            WriteLog("段落分析总时长" + (swtext.ElapsedMilliseconds / 1000).ToString("0") + "秒", "\\log\\log.txt", false);
        }

        /// <summary>
        /// 显示流程信息
        /// </summary>
        /// <param name="configModels"></param>
        private void ShowFlowModules(List<DataEngine.DataFlowParse.Model.ConfigModel> configModels)
        {
            foreach (DataEngine.DataFlowParse.Model.ConfigModel configurationFile in configModels)
            {
                ConfigModel configModel = new ConfigModel();
                configModel.Code = configurationFile.Code;
                configModel.ExecuteCode = configurationFile.ExecuteCode;
                configModel.ModuleName = configurationFile.ModuleName;
                configModel.Number = configurationFile.Number;
                if (configurationFile.ModuleName.IndexOf("流程") < 0 && !modules.Where(a => a.Code == configurationFile.Code).Any())
                {
                    modules.Add(configModel);
                }
                    
            }
            if (this.dataGridView1.InvokeRequired == false)
            {
                dataGridView1.DataSource = null;
                dataGridView1.DataSource = modules;
            }
            else
            {
                this.Invoke(new ModularModel(ShowFlowModules), new object[] { configModels });
            }
        }

        private void SetlabelMNText(string text)
        {
            if (labelMN.InvokeRequired)
            {
                Action<string> action = new Action<string>(SetlabelMNText);
                Invoke(action, new object[] { text });
            }
            else
            {
                labelMN.Text = labelMN.Text + text;
            }
        }

        private static object obj = new object();
        /// <summary>
        /// 将日志写入text
        /// </summary>
        /// <param name="content">内容</param>
        /// <param name="fileRelativePath">路径</param>
        /// <param name="tagDateTime">是否加时间分割线</param>
        public static void WriteLog(string content, string fileRelativePath, bool tagDateTime)
        {
            lock (obj)
            {
                string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + fileRelativePath;
                string filefolder = AppDomain.CurrentDomain.BaseDirectory + "\\Log";
                if (!Directory.Exists(filefolder))
                    Directory.CreateDirectory(filefolder);

                if (!File.Exists(filePath))
                    File.Create(filePath).Close();

                StreamWriter sw = new StreamWriter(filePath, true);
                if (tagDateTime)
                {
                    sw.WriteLine("\r\n" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----------------------------");
                }
                sw.WriteLine(content);
                sw.WriteLine("\r\n");
                sw.Close();
            }
        }
        /// <summary>
        /// 模型上述
        /// </summary>
        /// <param name="objModel">模型</param>
        /// <param name="node">树节点</param>
        private void LoopModelToTree(object objModel, TreeNode node)
        {
            Type TModel = objModel?.GetType();
            if (TModel != null)
            {
                PropertyInfo[] properties = TModel.GetProperties(BindingFlags.Public | BindingFlags.Instance); // 获取当前type公共属性
                foreach (PropertyInfo propertie in properties)
                {
                    switch (propertie.PropertyType.Name)
                    {
                        case "String":
                            object columnValue = propertie.GetValue(objModel, null);
                            node.Tag += "\n" + propertie.Name + ":" + Convert.ToString(columnValue);
                            break;
                        case "DataTable":
                        case "XmlNode":
                        case "Dictionary`2":
                        case "XmlDocument":

                            break;
                        default:
                            //case "List`1":
                            //case "AnalysisParameterModel":
                            //case "SourceDossierInfosModel":
                            //case "SD_ParagraphTXTModel":
                            if (propertie.PropertyType.IsClass && !propertie.PropertyType.IsGenericType)
                            {
                                if (propertie.PropertyType.Name == "ConfigurationFileModelList")
                                {
                                    continue;
                                }
                                Object ListO = propertie.GetValue(objModel, null);
                                TreeNode childnode = new TreeNode();
                                childnode.Text = propertie.PropertyType.Name;
                                node.Nodes.Add(childnode);
                                LoopModelToTree(ListO, childnode);
                            }
                            else if (propertie.PropertyType.IsGenericType)
                            {
                                if (propertie.Name == "ConfigurationFileModelList")
                                {
                                    continue;
                                }
                                // 如果是泛型集合，进行需要转
                                Object ListO = propertie.GetValue(objModel, null);
                                Type listModel = ListO?.GetType();
                                int count = Convert.ToInt32(listModel?.GetProperty("Count").GetValue(ListO, null));
                                for (int i = 0; i < count; i++)
                                {
                                    //将泛型集合的数据转对象集合，然后依次获取下标；
                                    object listItem = listModel.GetProperty("Item").GetValue(ListO, new object[] { i });

                                    TreeNode childnode = new TreeNode();
                                    childnode.Text = propertie.Name;
                                    node.Nodes.Add(childnode);
                                    LoopModelToTree(listItem, childnode);
                                }
                            }

                            break;
                    }

                }
            }
        }

        /// <summary>
        /// 日志输出@@@
        /// </summary>
        /// <param name="message"></param>
        /// <param name="messagetype"></param>
        public void LogMessage(string message, LogMessageType messagetype)
        {
            if (this.richTextBoxLog.InvokeRequired == false)
            {
                this.richTextBoxLog.AppendText(message);
                this.richTextBoxLog.AppendText("\r\n");
            }
            else
            {
                LogShow logshow = new LogShow(LogMessage);
                this.Invoke(logshow, new object[] { message, messagetype });
            }
        }

        public void LogMessage1(string message, LogMessageType messagetype)
        {

        }
        /// <summary>
        /// 设置进度条
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="nValue"></param>
        public void SetProcess(string fileId, int nValue, MainInputParameterModel inputParameterModel)
        {
            if (this.progressBar1.InvokeRequired == false)
            {
                this.progressBar1.Value = nValue;
                labelProgress.Text = nValue.ToString() + "%";
            }
            else
            {
                ProcessShow progressShow = new ProcessShow(SetProcess);
                this.Invoke(progressShow, new object[] { fileId, nValue });
            }
        }

        /// 设置模块执行的进度
        /// </summary>
        /// <param name="moduleName">模块名称</param>
        /// <param name="processValue">执行进度</param>
        public void SetModuleProcess(string moduleName, int processValue, MainInputParameterModel inputParameterModel)
        {
            if (this.currentModuleProcessBar.InvokeRequired == false && this.dataGridView1.InvokeRequired == false)
            {
                this.currentMprogressBar.Value = processValue;
                currentModuleProcessBar.Text = processValue.ToString() + "%";
                if (this.labelMN.Text.Split(':')[1] != moduleName)
                {
                    if (moduleName.IndexOf(@"\") > 0 || moduleName.IndexOf("：") > 0)
                    {
                        this.labelMN.Text = ":" + moduleName;
                    }
                    else
                    {
                        this.labelMN.Text = "当前运行模块:" + moduleName;
                    }
                }
                int moduleIndex = 0;
                int currentIndex = 0;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    moduleIndex++;
                    if (row.Cells["Column1"].Value.ToString().ToLower() == moduleName.Split('_')[0].ToLower())
                    {
                        currentIndex = moduleIndex;
                        if (processValue < 100)
                        {
                            SetProcess("", (currentIndex - 1) * 100 / dataGridView1.Rows.Count, inputParameterModel);
                            row.Cells["Column3"].Value = "运行中";
                        }
                        else if (processValue == 100)
                        {
                            row.Cells["Column4"].Value = (Convert.ToInt32(moduleName.Split('_')[2]) / 1000.0) + "s";
                            row.Cells["Column3"].Value = "结束";
                            SetProcess("", currentIndex * 100 / dataGridView1.Rows.Count, inputParameterModel);
                        }
                    }
                }
                if (currentIndex == dataGridView1.Rows.Count && uiWaitingBar1.Visible == true)
                    uiWaitingBar1.Visible = false;
                else
                {
                    if (currentIndex != dataGridView1.Rows.Count)
                        uiWaitingBar1.Visible = true;
                }
            }
            else
            {
                ProcessShow progressShow = new ProcessShow(SetModuleProcess);
                this.Invoke(progressShow, new object[] { moduleName, processValue, inputParameterModel });
            }
        }

        /// <summary>
        /// 动态加载dataTable显示分析结果
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeViewInfo_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Parent != null)
            {
                // 动态创建一个dataTable
                DataTable dt = new DataTable();
                TreeNode parentNode = e.Node.Parent;
                List<TreeNode> brotherNodes = new List<TreeNode>();
                TreeNodeCollection nodeList = parentNode.Nodes;
                foreach (TreeNode node in nodeList)
                {
                    if (node.Text == e.Node.Text)
                    {
                        if (dt.Columns.Count == 0)
                        {
                            string[] columns = node.Tag.ToString().Split('\n');
                            foreach (string column in columns)
                            {
                                if (column.IndexOf(":") > -1)
                                {
                                    dt.Columns.Add(column.Split(':')[0]);
                                }
                            }
                        }
                        brotherNodes.Add(node);
                    }
                }

                foreach (TreeNode node in brotherNodes)
                {
                    DataRow dr;
                    dr = dt.NewRow();
                    foreach (string col in node.Tag.ToString().Split('\n'))
                    {
                        if (col.IndexOf(":") > -1)
                        {
                            if (dt.Columns.Contains(col.Split(':')[0]))
                            {
                                dr[col.Split(':')[0]] = col.Split(':')[1];
                            }
                        }
                    }
                    dt.Rows.Add(dr);
                }

                // 使用GridView显示dataTable
                dataGridView1.DataSource = dt;
            }
            // richTextBoxInfo.Text = e.Node.Tag?.ToString().Substring(2);
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 消息框自动滚到到最新行位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void richTextBoxLog_TextChanged(object sender, EventArgs e)
        {
            //将光标位置设置到当前内容的末尾
            richTextBoxLog.SelectionStart = richTextBoxLog.Text.Length;
            //滚动到光标位置
            richTextBoxLog.ScrollToCaret();
        }

        private void FormMain_Resize(object sender, EventArgs e)
        {
            //dataGridView1.Width = richTextBoxInfo.Width;
        }

        private void buttonShowData_Click(object sender, EventArgs e)
        {
            if (dataContext != null)
            {
                FormShowData formShowData = new FormShowData(dataContext);
                formShowData.Show();
                //ShowData showData = new ShowData(dataContext);
                //showData.Show();
            }
            else
            {
                ShowInfoDialog("暂未分析出数据，请稍后再查看。");
            }

        }

        private void richTextBoxLog_TextChanged_1(object sender, EventArgs e)
        {
            richTextBoxLog.SelectionStart = richTextBoxLog.Text.Length;
            richTextBoxLog.ScrollToCaret();
        }

        private void comboBoxSourceName_TextUpdate(object sender, EventArgs e)
        {
        }

        private void comboSourceName_KeyDown(object sender, KeyEventArgs e)
        {
            //comboSourceName.DroppedDown = true;

        }

        private void comboSourceName_LocationChanged(object sender, EventArgs e)
        {

        }

        private void comboSourceName_Leave(object sender, EventArgs e)
        {
            //comboSourceName.DroppedDown = false;

        }

        private void comboSourceName_TextChanged(object sender, EventArgs e)
        {
            if (comboBoxcasetype.SelectedIndex > -1 && !string.IsNullOrEmpty(comboSourceName.Text))
                buttonImport.Enabled = true;
        }

        public void GetcomboSourceName()
        {
            SqlSysCommon sqlSysCommon = new SqlSysCommon("");
            comboSourceName.TextUpdate += (obj, args) =>
            {
                comboSourceName.Items.Clear();
                if (sysCaseTypeTable.Where(a => a.CaseTypeID == comboBoxcasetype.TreeView.SelectedNode.Name)?.ToList().Count > 0)
                {

                    comboSourceName.Items.Clear();
                    string code = sysCaseTypeTable.Where(a => a.CaseTypeID == comboBoxcasetype.TreeView.SelectedNode.Name)?.ToList()[0].CT_Code;
                    sysDocTypeTable = sqlSysCommon.GetDocTypeDataByCaseTypeID(code);
                    string s = comboSourceName.Text;
                    int n = comboSourceName.SelectionStart;
                    if (sysDocTypeTable != null && sysDocTypeTable.Count > 0)
                    {
                        if (!string.IsNullOrEmpty(s))
                        {
                            if (sysDocTypeTable.Where(a => a.CD_Name.IndexOf(s) > -1)?.ToList().Count > 0)
                            {
                                sysDocTypeTable = sysDocTypeTable.Where(a => a.CD_Name.IndexOf(s) > -1)?.ToList();
                            }
                        }
                        foreach (SYS_CaseType_DocType dr in sysDocTypeTable)
                        {
                            comboSourceName.Items.Add(dr.CD_Name.ToString().Trim() + "-" + dr.CD_Code.ToString().Trim());
                        }
                        comboSourceName.Select(comboSourceName.Text.Length, 0);
                        comboSourceName.DroppedDown = true;
                        //保持鼠标指针形状  
                        Cursor = Cursors.Default;
                    }
                }
            };
        }

        // 显示进度
        private void ProcessShow(string fileId, int processValue)
        {
            this.progressBar1.Value = processValue;
            labelProgress.Text = processValue + "%";
        }

        /// <summary>
        /// 向下查找关键字位置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btFindNext_Click(object sender, EventArgs e)
        {

            string input = textBoxCaseOnlyID.Text;
            List<string> list = new List<string>();
            System.Text.RegularExpressions.MatchCollection matchResulttite = System.Text.RegularExpressions.Regex.Matches(input, @"(?<=[\(\|])([\u4E00-\u9FFF]+)(?=[\)\|])");
            System.Text.RegularExpressions.MatchCollection matchResultvalue = System.Text.RegularExpressions.Regex.Matches(input, @"(?<=[\)]\s+).+$");
            if (matchResulttite != null && matchResulttite.Count > 0 && matchResultvalue != null && matchResultvalue.Count > 0)
            {
                string value = matchResultvalue[0].Value;
                foreach (System.Text.RegularExpressions.Match item in matchResulttite)
                {
                    list.Add(item.Value + @"\r" + value);
                }

            }
            string keyWords = textBoxKeyWord.Text.Trim();

            if (string.IsNullOrEmpty(keyWords))
            {
                ShowInfoDialog("请输入查询的关键字!!!");
                return;
            }

            var searchResult = richTextBoxLog.Find(keyWords, keyWordIndex, RichTextBoxFinds.None);
            if (searchResult == -1)
            {
                if (keyWordIndex == 0)
                {
                    ShowInfoDialog("未找到相关内容！");
                    return;
                }
                else
                {
                    ShowErrorDialog("没有了，还往下查啊！！！！再往下查就从头重新开始查咯！");
                    keyWordIndex = 0;
                    return;
                }
            }
            else
            {
                richTextBoxLog.Focus();
                richTextBoxLog.Select(searchResult, keyWords.Length);
                keyWordIndex = searchResult + keyWords.Length;
                btPro.Visible = true;
            }
        }

        /// <summary>
        /// 搜索关键字发生改变从头开始搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBoxKeyWord_TextChanged(object sender, EventArgs e)
        {
            keyWordIndex = 0;
            btPro.Visible = false;
        }

        /// <summary>
        /// 关键字查询  向上查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btPro_Click(object sender, EventArgs e)
        {
            string keyWords = textBoxKeyWord.Text.Trim();

            if (keyWordIndex == 0)
            {
                ShowWarningDialog("当前已经在起始位置，请先执行向下查询。");
                return;
            }
            var searchResult = richTextBoxLog.Find(keyWords, 0, keyWordIndex, RichTextBoxFinds.Reverse);
            if (searchResult == -1)
            {
                if (keyWordIndex == 0)
                {
                    ShowInfoDialog("未找到相关内容！");
                    return;
                }
                else
                {
                    ShowErrorDialog("没有了，还往上查啊！！！！再往上查就要上天了!");
                    keyWordIndex = 0;
                    return;
                }
            }
            else
            {
                richTextBoxLog.Focus();
                richTextBoxLog.Select(searchResult, keyWords.Length);
                keyWordIndex = searchResult - keyWords.Length;
                if (keyWordIndex < 0)
                    keyWordIndex = 0;
            }
        }

        /// <summary>
        /// 查看案件数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonCaseData_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(textBoxCaseOnlyID.Text))
            {
                HistoryFrom formShowCaseData = new HistoryFrom(dataContext.DataLayerOpt.OptimizationXml.OuterXml, null);
                formShowCaseData.ShowDialog();
            }
            else
            {
                ShowInfoDialog("请填写案件的唯一ID！");
            }
        }

        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == "Column5" && e.RowIndex >= 0)
            {

                string vlaue = dataGridView1.CurrentRow.Cells["Column1"].Value.ToString();
                Assembly assembly = Assembly.Load("LdtDataEngin.Moudle");
                Type moduleType = assembly.GetType(vlaue);
                MethodInfo methodInfo = moduleType.GetMethod("MoudleHandleResult", BindingFlags.Public | BindingFlags.Static);
                GetHandleResult = System.Delegate.CreateDelegate(typeof(HandleResultShow), methodInfo, true) as HandleResultShow;
                HandleResultModel handleResult = GetHandleResult();
                if (handleResult != null)
                {
                    switch (handleResult.ResultType)
                    {
                        case "1":
                            string xmlstr = handleResult.ResultData.ToString();
                            HistoryFrom historyFrom = null;
                            if (!string.IsNullOrWhiteSpace(xmlstr))
                            {
                                if (handleResult.AdditionalData != null)
                                {
                                    historyFrom = new HistoryFrom(FormatXml(xmlstr), handleResult.AdditionalData, dataContext?.DataLayerAns?.ElementNodeModelsList);
                                    // historyFrom = new SourDataFromcs(dataContext);
                                    //设置追溯xml
                                    string zsXml = ((List<RequestDataModel>)(handleResult.AdditionalData)).FirstOrDefault(x => x.RequestKey == "3")?.RequestParam;
                                    if (!string.IsNullOrWhiteSpace(zsXml))
                                    {
                                        JObject obj = JsonConvert.DeserializeObject<JObject>(zsXml);
                                        zsXml = obj["xmlContent"].ToString();
                                        historyFrom.zsXml = FormatXml(zsXml);
                                    }
                                }
                                else
                                {
                                    //historyFrom = new SourDataFromcs(dataContext);
                                    historyFrom = new HistoryFrom(FormatXml(xmlstr), null, dataContext?.DataLayerAns?.ElementNodeModelsList);
                                }

                            }

                            if (historyFrom != null)
                                historyFrom.ShowDialog();
                            break;
                        case "2":
                            if (handleResult.ResultData != null)
                            {
                                DataFrom dataFrom = new DataFrom(handleResult.ResultData);
                                dataFrom.ShowDialog();
                            }
                            break;
                        case "3":
                            if (handleResult.ResultData != null)
                            {
                                RequestForm requestForm = new RequestForm(handleResult.ResultData, dataContext);
                                requestForm.ShowDialog();
                            }
                            break;
                        case "4":
                            if (handleResult.ResultData != null)
                            {
                                ParagraphDataFrom paragraphDataFrom = new ParagraphDataFrom(handleResult.ResultData);
                                paragraphDataFrom.ShowDialog();
                            }
                            break;
                        default:
                            break;
                    }

                }

            }
        }

        /// <summary>
        /// xml内容格式化
        /// </summary>
        /// <param name="sUnformattedXml"></param>
        /// <returns></returns>
        public static string FormatXml(string sUnformattedXml)
        {
            XmlDocument xd = new XmlDocument();
            xd.LoadXml(sUnformattedXml);
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            XmlTextWriter xtw = null;
            try
            {
                xtw = new XmlTextWriter(sw);
                xtw.Formatting = System.Xml.Formatting.Indented;
                xtw.Indentation = 1;
                xtw.IndentChar = '\t';
                xd.WriteTo(xtw);
            }
            finally
            {
                if (xtw != null)
                    xtw.Close();
            }
            return sb.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            FormBack form = new FormBack();
            form.Show();
            form.Owner = this;
        }
        /// <summary>
        /// 菜单栏单机
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            switch (e.ClickedItem.Name)
            {
                case "toolStripMenuItemElementTODoc":
                    ToolsForm.FormElementToDoc formElementToDoc = new ToolsForm.FormElementToDoc();
                    formElementToDoc.ShowDialog();
                    break;
                case "toolStripMenuItemXmlToDocument":
                    ToolsForm.FormXmlToDocument formXmlTo = new ToolsForm.FormXmlToDocument();
                    formXmlTo.ShowDialog();
                    break;
                case "toolStripMenuItemDataConfig":
                    ToolsForm.FormSeetingCenter formSeetingCenter = new ToolsForm.FormSeetingCenter(_configuration);
                    formSeetingCenter.setConfigEvent += UpdateSettingCenter;
                    formSeetingCenter.ShowDialog();
                    if (!string.IsNullOrEmpty(formSeetingCenter.settingcenterstr))
                    {
                        ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(_configuration);
                        LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.SetConfiguration(formSeetingCenter.settingcenterstr);
                        LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.ClearDic();

                        ISettingCenter settingCenter = (ISettingCenter)new SettingCenterClient(LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.GetConfigConn(), "LDT71_WordParseAPI", httpHelper);
                        LdtJudge.DataEngine.CallInterface.CommHelp.FreeSQLHelp.freesqlDb = new LdtCommonFreeSql.FreesqlDb(null, settingCenter);
                        var ta = Task.Run(() => { configRetrieval = new ConfigRetrieval(_configuration, configManagerHandle, settingCenter); });
                        ta.Wait();
                        LoadSysCaseTypeData();
                        comboBoxcasetype.TreeView.AfterExpand += TreeView_AfterExpandCaseType;
                        GetcomboSourceName();
                    }
                    break;
                case "toolStripMenuItemDataQuery":
                    Ldt.CaseRetrievalApp.FormCaseRetrieval formCaseRetrieval = new CaseRetrievalApp.FormCaseRetrieval();
                    formCaseRetrieval.ShowDialog();
                    break;
                case "toolStripMenuItemRuleTest":
                    FormRuleTest frRuleTest = new FormRuleTest();
                    frRuleTest.ShowDialog();
                    break;
                default:
                    break;
            }

        }

        private void buttonShowDynamicData_Click(object sender, EventArgs e)
        {
            if (dataContext != null)
            {
                ShowDynamicData showDynamicData = new ShowDynamicData(dataContext);
                showDynamicData.Show();
            }
            else
            {
                ShowInfoDialog("暂未分析出数据，请稍后再查看。");
            }
        }

        private void paneltop_Paint(object sender, PaintEventArgs e)
        {

        }

        private void uiLabel1_Click(object sender, EventArgs e)
        {

        }

        private void button11_Click(object sender, EventArgs e)
        {
            SourDataFromcs historyFrom = new SourDataFromcs(dataContext);
            historyFrom.ShowDialog();
        }

        /// <summary>
        /// 修改配置中心地址
        /// </summary>
        private void UpdateSettingCenter(string centerAddress)
        {
            _configuration["appsettings:setting_center_address"] = centerAddress;
            ConfigManagerHandle configManagerHandle = new ConfigManagerHandle(_configuration);
            ISettingCenter settingCenter = new SettingCenterClient(centerAddress, "LDT71_WordParseAPI", httpHelper);
            var ta = Task.Run(() => { configRetrieval = new ConfigRetrieval(_configuration, configManagerHandle, settingCenter); });
            ta.Wait();
        }

        private void toolStripMenuItemElementTODoc_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 案由文本框只能输入数字和字母
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txbCaseCause_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((e.KeyChar >= 48 && e.KeyChar <= 57) || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || e.KeyChar == 8)
                {
                    e.Handled = false;
                }
                else
                {
                    if ((e.KeyChar >= 'a' && e.KeyChar <= 'z') || e.KeyChar == 8)
                    {
                        e.Handled = false;
                    }
                    else if (e.KeyChar == ',')
                    {
                        e.Handled = false;
                    }
                    else e.Handled = true;
                }
            }
        }

        /// <summary>
        /// 数据源删除按钮
        /// </summary>
        private void sourceRemoveButton_Click(object sender, EventArgs e)
        {
            if (comboBoxcasetype.TreeView.SelectedNode.Nodes.Count > 0)
            {
                comboBoxcasetype.Text = "";
                ShowWarningDialog("选择的案件类型无效，请重新选择！");
                return;
            }
            if (string.IsNullOrWhiteSpace(caseIdTextBox.Text))
            {
                ShowWarningDialog("请输入案件ID！");
                return;
            }
            if (string.IsNullOrWhiteSpace(sourceTextBox.Text))
            {
                ShowWarningDialog("请输入数据源编号！");
                return;
            }
            string caseType = comboBoxcasetype.Text;
            string caseId = caseIdTextBox.Text;
            string sourceCode = sourceTextBox.Text;
            string msgState = string.Empty;
            string errMsg = string.Empty;
            Ldt.DataEngin.Assemble.Main main = new Ldt.DataEngin.Assemble.Main();
            main.LogShow = new LogShow(LogMessage);
            main.InstrumentDeletion(caseType, caseId, sourceCode, out msgState, out errMsg);
        }
    }

    public delegate void SetConfigRetrievalHandlear(string settingCenterAddress);

    public class ConfigModel
    {
        /// <summary>
        /// 文件名称
        /// </summary>
        public string ExecuteCode { get; set; }
        /// <summary>
        /// 文件编号
        /// </summary>
        public string Code { get; set; }

        /// <summary>
        /// 模块名称
        /// </summary>
        public string ModuleName { get; set; }

        /// <summary>
        /// 序号
        /// </summary>
        public string Number { get; set; }

        /// <summary>
        /// 状态
        /// </summary>
        public string State { get; set; }

        /// <summary>
        /// 用时
        /// </summary>
        public string Endtiem { get; set; }
    }



}
